<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="源单编号" prop="sourceCode">
        <el-input
          v-model="queryParams.sourceCode"
          placeholder="请输入源单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="单据日期" prop="docTime">
        <el-date-picker clearable
                        v-model="queryParams.docTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择单据日期">
        </el-date-picker>
      </el-form-item>


      <el-form-item label="供应商" prop="supId">
        <el-input
          v-model="queryParams.supId"
          placeholder="供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务员" prop="businessUserId">
        <el-input
          v-model="queryParams.businessUserId"
          placeholder="请输入业务员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['finance:payment:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['finance:payment:edit']"
        >修改
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['finance:payment:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paymentList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="主键" align="center" prop="id"/>-->
      <el-table-column label="单据编号" align="center" prop="code" width="200" fixed="left">
        <template slot-scope="scope">
          <el-button type="text" @click="info(scope.row)">{{ scope.row.code }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="源单号" prop="sourceCode" width="200"/>
      <el-table-column label="单据类型" prop="codeTypeName" width="200"/>
      <!--      <el-table-column label="源单编号" align="center" prop="sourceCode"/>-->
      <el-table-column label="总金额" align="center" prop="totalAmount"/>
      <el-table-column label="已核销金额" align="center" prop="verifiedAmount" width="100"/>
      <el-table-column label="单据日期" align="center" prop="docTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.docTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据阶段" align="center" prop="docStage">
        <template slot-scope="scope">
          <span v-if="scope.row.docStage == 0">编制完</span>
          <span v-if="scope.row.docStage == 1">执行中</span>
          <span v-if="scope.row.docStage == 2">执行完</span>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="docMakeUserName"/>
      <el-table-column label="供应商" align="center" prop="supName" width="200"/>
      <el-table-column label="业务员" align="center" prop="businessUserName"/>
      <el-table-column label="审批结果" align="center" prop="approvalResult" width="100">
        <template slot-scope="scope">
          <!--          <el-tag  v-if="scope.row.approvalResult == 0 || scope.row.approvalResult == undefined || scope.row.approvalResult == null">待审核</>-->
          <el-tag type="success" v-if="scope.row.approvalResult == 1">审核通过</el-tag>
          <el-tag type="danger" v-if="scope.row.approvalResult == 2">审核不通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批意见" align="center" prop="approvalRemark"/>
      <el-table-column label="审批人" align="center" prop="approvalUserName"/>
      <el-table-column label="是否生效" align="center" prop="isEffect">
        <template slot-scope="scope">
          <span
            v-if="scope.row.isEffect == 0 || scope.row.isEffect == undefined || scope.row.isEffect == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否关闭" align="center" prop="isClose">
        <template slot-scope="scope">
          <span v-if="scope.row.isClose == 0 || scope.row.isClose == undefined || scope.row.isClose == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="是否作废" align="center" prop="isCancel">
        <template slot-scope="scope">
          <span
            v-if="scope.row.isCancel == 0 || scope.row.isCancel == undefined || scope.row.isCancel == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" prop="updateBy"/>
      <el-table-column label="修改时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="300" fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['finance:payment:edit']"
            :disabled="scope.row.approvalResult!=0"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['finance:payment:remove']"
            v-show="scope.row.approvalResult==0"
          >删除
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-thumb"
                     @click="approval(scope.row)"
                     :disabled="!(scope.row.approvalResult===0)">
            审 核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改付款单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1300px" append-to-body
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" inline label-width="80px">
        <el-form-item label="单据编号" prop="code">
          <el-input v-model="form.code" placeholder="单据编号" readonly/>
        </el-form-item>
        <el-form-item label="单据日期" prop="docTime">
          <el-date-picker clearable
                          v-model="form.docTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择单据日期"
                          :disabled="isInfo">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商" prop="supId">
          <!--          <el-input v-model="form.supId" placeholder="请输入供应商id" />-->
          <!--          <el-select v-model="form.supId" placeholder="请选择" @change="supSelectChanged" :disabled="cgrkList.length>0">-->
          <el-select v-model="form.supId" placeholder="请选择" @change="supSelectChanged"
                     :disabled="cgddList.length>0 || isInfo ">
            <el-option
              v-for="item in supplierList"
              :key="item.id"
              :label="item.supName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <template>
          <el-button type="text" v-if="isFormMore" @click="isFormMore = false">收起</el-button>
          <el-button type="text" v-else @click="isFormMore = true">更多</el-button>
        </template>
        <div v-show="isFormMore">

          <el-form-item label="源单编号" prop="sourceCode">
            <el-input v-model="form.sourceCode" placeholder="源单编号"/>
          </el-form-item>
          <el-form-item label="总金额" prop="totalAmount">
            <el-input v-model="form.totalAmount" placeholder="总金额" readonly/>
          </el-form-item>
          <el-form-item label="已核销金额" prop="verifiedAmount" label-width="100">
            <el-input v-model="form.verifiedAmount" placeholder="已核销金额" readonly/>
          </el-form-item>

          <el-form-item label="单据阶段" prop="docStage">
            <!--            <el-input v-model="form.docStage" placeholder="单据阶段" />-->
            <el-select v-model="form.docStage" disabled>
              <el-option :value="0" label="编制完">编制完</el-option>
              <el-option :value="1" label="执行中">执行中</el-option>
              <el-option :value="2" label="执行完">执行完</el-option>
            </el-select>

          </el-form-item>
          <el-form-item label="制单人" prop="docMakeUserId">
            <el-input v-model="form.docMakeUserName" placeholder="制单人"/>
          </el-form-item>

          <el-form-item label="业务员" prop="businessUserId">
            <el-input v-model="form.businessUserName" placeholder="业务员"/>
          </el-form-item>
          <el-form-item label="审批结果" prop="approvalResult">
            <!--            <el-input v-model="form.approvalResult" placeholder="审批结果"/>-->
            <el-select v-model="form.approvalResult" disabled>
              <el-option :value="0" label="待审核">待审核</el-option>
              <el-option :value="1" label="通过">通过</el-option>
              <el-option :value="2" label="不通过">不通过</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审批意见" prop="approvalRemark">
            <el-input v-model="form.approvalRemark" placeholder="审批意见" readonly/>
          </el-form-item>
          <el-form-item label="审批人" prop="approvalUserId">
            <el-input v-model="form.approvalUserName" placeholder="审批人" readonly/>
          </el-form-item>
          <el-form-item label="是否生效" prop="isEffect">
            <!--            <el-input v-model="form.isEffect" placeholder="是否生效" readonly/>-->
            <el-select v-model="form.isEffect" disabled>
              <el-option :value="0" label="否">否</el-option>
              <el-option :value="1" label="是">是</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否关闭" prop="isClose">
            <!--            <el-input v-model="form.isClose" placeholder="是否关闭" readonly/>-->
            <el-select v-model="form.isClose" disabled>
              <el-option :value="0" label="否">否</el-option>
              <el-option :value="1" label="是">是</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否作废" prop="isCancel">
            <!--            <el-input v-model="form.isCancel" placeholder="是否作废" readonly/>-->
            <el-select v-model="form.isCancel" disabled>
              <el-option :value="0" label="否">否</el-option>
              <el-option :value="1" label="是">是</el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-tabs v-model="activeName">
          <el-tab-pane label="采购订单" name="first">
            <!--          <el-button plain type="primary" icon="el-icon-plus" @click="addBjd" :disabled="!(form.supId>0)">比价单</el-button>-->
            <el-button plain type="primary" icon="el-icon-plus" @click="addCgdd"
                       :disabled="!(form.supId >0) || isInfo ">
              采购订单
            </el-button>
            <el-button type="primary" icon="el-icon-minus" @click="removeCgdd" :disabled="isInfo">移除
            </el-button>
            <el-table :data="cgddList"
                      border
                      @selection-change="handleSelectionChangeCgdd"
            >
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column prop="code" label="单据编号"/>
              <el-table-column label="单据日期" prop="docTime">

              </el-table-column>
              <el-table-column prop="totalAmount" label="订单金额"/>
              <el-table-column prop="paidAmount" label="已付金额"/>
            </el-table>

          </el-tab-pane>
          <el-tab-pane label="明细" name="second">
            <!--          <el-button type="primary" @click="addGoods">添加</el-button>-->
            <!--          <el-button type="primary" icon="el-icon-minus" @click="removeOrderGoods"-->
            <!--                     v-show="selectOrderGoodList.length>0">移除-->
            <!--          </el-button>-->
            <el-table :data="yfkDetailsList"
                      border
                      @selection-change="handleSelectionChangeCgddDetails"
            >
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column prop="sourceCode" label="源单编号"/>
              <el-table-column prop="paymentMethod" label="支付方式">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.paymentMethod" :disabled="isInfo">
                    <el-option
                      v-for="item in [{id:0,payMethod:'现金'},{id:1,payMethod:'银行转账'}]"
                      :key="item.id"
                      :label="item.payMethod"
                      :value="item.payMethod">
                    </el-option>
                  </el-select>
                </template>

              </el-table-column>
              <el-table-column prop="accountId" label="资金账户">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.accountId" :disabled="isInfo">
                    <el-option
                      v-for="item in accountList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>

              </el-table-column>
              <el-table-column prop="totalAmount" label="预付金额">
                <template slot-scope="scope">
                  <!--                <MyNumberInput-->
                  <MyNumberInput :point="2" :max="scope.row.maxAmount" placeholder="请输入金额"
                                 v-model.number="scope.row.totalAmount" :disabled="isInfo"></MyNumberInput>
                </template>
              </el-table-column>
            </el-table>
            <div class="demo-input-suffix" v-show="isApproval">
              审核意见：
              <el-input
                v-model="form.approvalRemark" style="width: 300px">
              </el-input>
              审核结果：
              <el-select v-model="form.approvalResult">
                <el-option
                  v-for="item in [{id:0,value:0,name:'请选择'},{id:1,value:1,name:'通过'},{id:2,value:2,name:'不通过'}]"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"/>
              </el-select>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-show="!isApproval">确 定</el-button>
        <el-button type="primary" @click="submitFormApproval" v-show="isApproval">审核</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择采购订单"
      :visible.sync="selectCgddDialogVisible"
      width="1000px"
      :close-on-click-modal="false"
      :close-on-press-escape="false">

      <SelectCgdd ref="selectCgddComponent" :params="queryParams"/>
      <span slot="footer" class="dialog-footer">
     <el-button @click="cancelSelectCgdd">取 消</el-button>
    <el-button type="primary" @click="sureSelectCgdd">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  listPayment,
  getPayment,
  delPayment,
  addPayment,
  updatePayment,
  approvalPayment
} from "@/api/finance/paymentAdvance";
import {listSupplies} from "@/api/basedata/supplies";
import {listAccount} from "@/api/finance/account";
import MyNumberInput from "@/views/caigou/gysbj/MyNumberInput.vue";
import SelectCgdd from "@/views/finance/paymentAdvance/SelectCgdd.vue";

export default {
  name: "Payment",
  components: {MyNumberInput, SelectCgdd},
  data() {
    return {
      isInfo: false,
      isApproval: false,
      accountList: [],
      selectCgddDialogVisible: false,
      yfkDetailsList: [],
      cgddList: [],
      activeName: 'first',/*second*/
      supplierList: [],
      isFormMore: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 付款单表格数据
      paymentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        sourceCode: null,
        codeType: 12,
        totalAmount: null,
        verifiedAmount: null,
        docTime: null,
        docStage: null,
        docMakeUserId: null,
        supId: null,
        businessUserId: null,
        approvalResult: null,
        approvalRemark: null,
        approvalUserId: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        orderByColumn: 'create_time',
        isAsc: 'desc'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          {required: true, message: "单据编号不能为空", trigger: "blur"}
        ],
        docTime: [
          {required: true, message: "单据日期不能为空", trigger: "blur"}
        ],
        supName: [
          {required: true, message: "供应商不能为空", trigger: "blur"}
        ],
        supId: [
          {required: true, message: "供应商不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    info(row) {
      this.activeName = 'second';/*second*/
      this.isInfo = true;
      this.initBaseData()
      this.reset();
      const id = row.id || this.ids
      getPayment(id).then(response => {
        this.form = response.data;
        this.yfkDetailsList = this.form.list;
        this.open = true;
        this.title = "查看-付款申请";
      });
    },
    supSelectChanged() {
      this.cgddList = [];
      this.yfkDetailsList = [];
    },
    submitFormApproval() {
      if (this.form.approvalResult == null || this.form.approvalResult == undefined || this.form.approvalResult == '') {
        this.$modal.msgWarning("选择审核结果")
        return
      }
      if (this.form.approvalResult == 1) {
        this.form.isEffect = 1
        this.form.docStage = 1
      } else if (this.form.approvalResult == 2) {
        this.form.isEffect = 0
        this.form.docStage = 2
      }

      approvalPayment(this.form).then(response => {
        this.$modal.msgSuccess("审核成功");
        this.open = false;
        this.getList();
      });
    },
    approval(row) {
      this.open = true;
      this.handleUpdate(row)
      this.isApproval = true;
    },
    sureSelectCgdd() {
      let returnSelectCgddList = this.$refs.selectCgddComponent.returnSelectCgddList();
      console.log('returnSelectCgddList', returnSelectCgddList)
      this.cgddList = returnSelectCgddList;
      returnSelectCgddList.forEach(item => {
        this.yfkDetailsList.push({
          ...item,
          totalAmount: item.totalAmount - item.paidAmount - item.advanceAmount,
          maxAmount: item.totalAmount - item.paidAmount - item.advanceAmount,
          sourceCode: item.code,
          paymentMethod: '现金'
        })
      })
      this.selectCgddDialogVisible = false
    },
    cancelSelectCgdd() {
      this.selectCgddDialogVisible = false;
    },
    handleSelectionChangeCgddDetails() {

    },
    handleSelectionChangeCgdd(val) {

    },
    removeCgdd() {
      this.yfkDetailsList = [];
      this.cgddList = [];
    },
    addCgdd() {
      this.selectCgddDialogVisible = true;
      this.$refs.selectCgddComponent.setSupId(this.form.supId);
    },
    // 新增初始化数据
    initBaseData() {
      //获取所有供应商
      listSupplies().then(res => {
        this.supplierList = res.rows
      })
      this.isFormMore = false;
      this.isApproval = false;
      this.yfkDetailsList = [];
      this.cgddList = [];
      listAccount().then(res => {
        this.accountList = res.rows;
        console.log(res);
      })
    },
    /** 查询付款单列表 */
    getList() {
      this.loading = true;
      listPayment(this.queryParams).then(response => {
        this.paymentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: 'YFK-' + Date.now(),
        sourceCode: null,
        codeType: 12,
        totalAmount: null,
        verifiedAmount: null,
        docTime: null,
        docStage: null,
        docMakeUserId: null,
        supId: null,
        businessUserId: null,
        approvalResult: null,
        approvalRemark: null,
        approvalUserId: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        list: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预付款单";
      this.initBaseData();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isApproval = false;
      this.reset();
      this.initBaseData();
      const id = row.id || this.ids
      getPayment(id).then(response => {
        this.form = response.data;
        this.yfkDetailsList = response.data.list;
        this.open = true;
        this.title = "修改预付款单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.isInfo) {
        this.isInfo = false;
        return;
      }
      this.form.list = this.yfkDetailsList;
      if (this.form.list.length == 0) {
        this.$modal.msgWarning("请选择采购订单")
        return
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.updateBy = this.$store.getters.name
            updatePayment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.createBy = this.$store.getters.name
            addPayment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除预付款单编号为"' + ids + '"的数据项？').then(function () {
        return delPayment(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('finance/payment/export', {
        ...this.queryParams
      }, `payment_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
